<template>
  <div id="model_edit">
    <h1 v-if="isUpdate">编辑 <span v-text="name"></span></h1>
    <h1 v-else>创建 <span v-text="name"></span></h1>
    <el-form ref="beanForm" :model="beanActual"
        :rules="rules" @validate="formValidated">
      <el-form-item v-for="field in fieldsWithoutId" :key="field.id" :label="field.name" :prop="field.name">
        <el-input v-if="field.dataType == 'VARCHAR' || field.dataType == 'UUID' || field.dataType == 'CLOB'"
            :type="inputType(field.dataType)" :maxlength="field.precisionOrLength" v-model="beanActual[field.name]"/>
        <el-input-number v-if="field.dataType == 'INT32' || field.dataType == 'INT64' || field.dataType == 'DECIMAL'" v-model="beanActual[field.name]"/>
        <el-date-picker v-if="field.dataType == 'DATE' || field.dataType == 'DATETIME'"
            :type="inputType(field.dataType)" :format="field.dateTimePattern" v-model="beanActual[field.name]"/>
        <el-time-select v-if="field.dataType == 'TIME'" :format="field.dateTimePattern" v-model="beanActual[field.name]"/>
      </el-form-item>
      <el-form-item>
        <error-alert :errorMessage="errorMessage" @ok="errorOk"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :disabled="invalid" :loading="submitting" @click="submit()">提交</el-button>
        <el-button @click="cancel()">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import elementLayout from "../plugins/element/layout.js";
import elementForm from "../plugins/element/form.js";
import elementTable from "../plugins/element/table.js";
import elementInput from "../plugins/element/input.js";
import elementInputNumber from "../plugins/element/input_number.js";
import elementDatePicker from "../plugins/element/date_picker.js";
import elementButton from "../plugins/element/button.js";

import http from "../util/http.js";

import ErrorAlert from "../components/ErrorAlert.vue";
// import { validateNotBlank, validateSQLIdentifier } from "../plugins/element/validators.js";

const component = {
  name: "bean_edit",
  props: {
    bean: {
      validator(value) {
        if (typeof(value) !== "string") {
          return false;
        }
        try {
          const bean = JSON.parse(value);
          return typeof(bean) === "object";
        } catch (e) {
          console.error(e);
          return false;
        }
      },
      required: true
    },
    fields: {
      validator(value) {
        if (typeof(value) !== "string") {
          return false;
        }
        try {
          const fields = JSON.parse(value);
          if (!Array.isArray(fields)) {
            return false;
          }
          for (const field of fields) {
            if (typeof(field) !== "object" || typeof(field.name) !== "string") {
              return false;
            }
          }
          return true;
        } catch (e) {
          console.error(e);
          return false;
        }
      },
      requird: true
    }
  },
  data() {
    return {
      beanActual: {
        id: null
      },

      submitting: false,
      errorMessage: "",

      isFieldValid: {
      },
      rules: {
      }
    };
  },
  computed: {
    fieldsWithoutId() {
      const beanPermissions = this.$store.state.beanPermissions
          .filter(item => item.bean.id === this.$route.query.id);
      return JSON.parse(this.fields).filter(field => {
        if (field.name === "id") {
          return false;
        }
        if (beanPermissions.length === 1 && beanPermissions[0].permissionType === "EDITOR" &&
            field.name === 'status') {
          return false;
        }
        return true;
      });
    },
    isUpdate() {
      return !!this.$route.query.beanId;
    },
    invalid() {
      return false;
    }
  },
  created() {
    this.beanActual = JSON.parse(this.bean);
    this.refresh();
  },
  methods: {
    refresh() {
      if (!this.isUpdate) {
        return;
      }
      this.$store.commit("setLoading");
      http.get( http.receiveJSON({
        url: "/managed-bean/" + this.$route.query.name + "/" + this.$route.query.beanId
      }) ).then(response => {
        this.beanActual = response.data.content;

        this.$store.commit("unsetLoading");
      }).catch((ex) => {
        console.error(ex);
        this.$store.commit("unsetLoading");
      });
    },

    formValidated(prop, valid) {
      this.isFieldValid[prop] = valid;
    },
    submit() {
      this.$refs.beanForm.validate(isValid => {
        if (!isValid) {
          return;
        }
        this.submitting = true;
        http.post( http.receiveJSON(http.sendJSON({
          url: "/managed-bean/" + this.$route.query.name,
          data: this.beanActual
        })) ).then(response => {
          if ((response.data && response.data.code) !== "ok") {
            throw new Error('The response code is not "ok"');
          }
          this.submitting = true;
          this.$router.back();
        }).catch((ex) => {
          console.error(ex);
          this.errorMessage = (this.isUpdate ? "更新" : "创建") + " Bean 出错";
        });
      });
    },
    cancel() {
      this.$router.back();
    },
    errorOk() {
      this.errorMessage = "";
    },

    inputType (dataType) {
      switch (dataType) {
        case "VARCHAR":
        case "CLOB":
          return "textarea";
        case "DATETIME":
          return "datetime";
        case "DATE":
          return "date";
      }
      return "text";
    }
  },
  components: {
    ErrorAlert
  }
};

elementLayout(component);
elementForm(component);
elementTable(component);
elementInput(component);
elementInputNumber(component);
elementDatePicker(component);
elementButton(component);

export default component;
</script>

<style scoped>
#fields_header {
  display: flex;
  justify-content: space-between;
}
#fields_header h3, #fields_header button.el-button {
  align-self: center;
}
#fields_header h3 {
  font-family: STSong, NSimSun, SimSun, Times, "Times New Roman", Georgia, serif;
  font-size: 1.1em;
}
</style>
